package com.example.waterorder.interceptor;


import com.example.waterorder.dto.UserDto;
import com.example.waterorder.tools.Result;
import com.example.waterorder.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class AuthenticationFilter implements HandlerInterceptor {

    @Resource
    private UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        if (uri.contains("/login") || uri.contains("/register") || uri.contains("/swagger-ui")) {
            return true;
        }
        // //获取请求头中的token
        String token = null;
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(authHeader)) {
            token = authHeader;
        } else {
            if (request.getHeader("token") != null) {
                token = request.getHeader("token");
            } else {
                token = request.getParameter("token");
            }
        }
        UserDto userDto = new UserDto();
//        System.out.println(token);
        userDto.setToken(token);
        boolean flag = userService.verify(userDto);
        if (!flag) {
            String json = new ObjectMapper().writeValueAsString(new Result(false, "登录信息失效", 401));

            response.setContentType("application/json; charset=UTF-8");

            response.getWriter().println(json);
            return false;
        }
        return true;
    }
}